/* -----------------------------------------------------
 iCompose
 DownloadView.h
 
 Created by Team: THE BEARD on 10/11/09.
 
 Members who contributed to this file:
 1. Ethan Holmes
 2. Woo Jin Chang
 
 List of changes to previous member:
 Version 1:
 Nov 13, 2009 (Woo Jin)
 - implemented Downloading method
 Nov 14, 2009 (Woo Jin)
 - revised Downloading method
 
 Simon Fraser University, 2009.
 ----------------------------------------------------- */


#import "DownloadView.h"


@implementation DownloadView

@synthesize staffNames;
@synthesize dataFilePathDataBase;
@synthesize name;
@synthesize dataFilePath;

-(IBAction)back {
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(IBAction)Downloading {
	NSString *anURL = [[NSString alloc] initWithString:@"http://practiceobjc.zxq.net/uploads/"];
	anURL = [anURL stringByAppendingString:name];
	NSLog(anURL);
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:anURL]
											  cachePolicy:NSURLRequestUseProtocolCachePolicy
										  timeoutInterval:60.0];
	// create the connection with the request
	// and start loading the data
	NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if (theConnection) {
		NSLog(@"connection succeed!");
		NSURLResponse* response;
		NSError* error;
		NSData* receiveData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
		
		NSLog(@"%d bytes", [receiveData length]);
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex: 0];
		dataFilePath = [documentsDirectory stringByAppendingPathComponent: name];
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		
		if ([fileManager createFileAtPath:dataFilePath contents:receiveData attributes: nil] ==NO) {
			NSLog(@"Couldn't create the copy");

		}
		
		NSLog(@"%@", dataFilePath);
		
	}
	
	else {
		NSLog(@"Connection failed!");
	}
	[self decodeAndAddStaff];
}

-(void)getAllName
{
	staffNames = [[NSMutableArray alloc] init];
	
	if (sqlite3_open([[self dataFilePathDataBase] UTF8String], &database) != SQLITE_OK)
	{
		sqlite3_close(database);
		NSAssert(0, @"Failed to open database");
	}
	else
	{
		const char *sqlStatment = "SELECT * FROM STAFF;";
		sqlite3_stmt *compiledStatment;
		if(sqlite3_prepare_v2(database, sqlStatment, -1, &compiledStatment, nil) != SQLITE_OK)
		{
			sqlite3_close(database);
			NSAssert(0, @"Failed to select database");
		}
		else
		{
			while(sqlite3_step(compiledStatment) == SQLITE_ROW)
			{
				//NSLog(@"1");
				//NSLog(@"%@", sqlite3_column_text(compiledStatment, 1));
				char *aName = (char *)sqlite3_column_text(compiledStatment, 0);
				
				NSString *theName = [[NSString alloc] initWithUTF8String: aName];
				
				//NSLog(aName);
				[staffNames addObject:theName];
				
				[theName release];
			}
		}
		sqlite3_finalize(compiledStatment);
	}
	sqlite3_close(database);
}

-(void)downloadDB
{
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://practiceobjc.zxq.net/uploads/staffDataBase.sql"]
											  cachePolicy:NSURLRequestUseProtocolCachePolicy
										  timeoutInterval:60.0];
	// create the connection with the request
	// and start loading the data
	NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if (theConnection) {
		NSLog(@"connection succeed!");
		NSURLResponse* response;
		NSError* error;
		NSData* receiveData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
		
		NSLog(@"%d bytes", [receiveData length]);
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex: 0];
		dataFilePathDataBase = [documentsDirectory stringByAppendingPathComponent: @"staffDataBase.sql"];
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		
		if ([fileManager createFileAtPath:dataFilePathDataBase contents:receiveData attributes: nil] ==NO) {
			NSLog(@"Couldn't create the copy");
			
		}
		
		NSLog(@"%@", dataFilePathDataBase);
		
	}
	
	else {
		NSLog(@"Connection failed!");
	}
}

-(void)decodeAndAddStaff
{
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if([fileManager fileExistsAtPath:dataFilePath]) {
		NSLog(@"Data file found. Reading into memory.");
		NSMutableData *theData;
		NSKeyedUnarchiver *decoder;
		MainView *view;
		
		theData = [NSData dataWithContentsOfFile: dataFilePath];
		decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData: theData];
		view = [decoder decodeObjectForKey:kDataKey];
		iComposeAppDelegate *mainDelegate = (iComposeAppDelegate*)[[UIApplication sharedApplication] delegate];
		[mainDelegate.staffArray addObject:view];
		//[self setStaffArray: tempArray];
		[decoder finishDecoding];
		[decoder release];
	}
}
/*
-(void)connectDataBase{
MCPConnection *theConnec;

MCPResult *theRes;

//initialize connection string vars

NSString *dbURL = @"XXXXXX";

NSString *userName = @"XXXXXX";

NSString *pass = @"XXXXXX";

//open connection to database

	theConnec = [theConnec initToHost:dbURL withLogin:userName password:pass usingPort:3306];

//NSLog(@"The connection to database was successfull");

	[theConnec selectDB:@"XXXXXX"];

//{

// NSLog(@"Database found");

//}

//else

//{

// NSLog(@"Database not found");

//}

	theRes = [theConnec queryString:@"select * from seahawk_tag"];

	//get the number of rows

	NSInteger numberOfRows = [theRes numofRows];


	NSLog(@"Query of MySQL Database %@", numberOfRows);

	//return NSApplicationMain(argc, (const char **) argv);

	[theConnec release];
}
 */
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	//staffNames should be updated from SQL
	[self downloadDB];
	[self getAllName];
	
	for (int i = 0; i < [staffNames count]; i++) {
		NSLog(@"%@", [staffNames objectAtIndex: i]);
	}
    [super viewDidLoad];
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	//iComposeAppDelegate *mainDelegate = (iComposeAppDelegate*)[[UIApplication sharedApplication] delegate];
    return [staffNames count];//[mainDelegate.staffArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	
	NSUInteger row = [indexPath row];
	if ([staffNames count] != 0) {
		cell.textLabel.text = [staffNames objectAtIndex:row];
		//cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	}
	//cell.textLabel.text = @"HELLO";
	//cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = [indexPath row];
	name = [[NSString alloc] initWithString:[staffNames objectAtIndex:row]];
	//[self presentModalViewController:mainView animated: YES];
	//code for specialized mainView do not impemement this method.
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (void)dealloc {
    [super dealloc];
}


@end
